package com.ndp.fb.rdb.mongo.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.mongodb.BasicDBObject;
import com.mongodb.Bytes;
import com.mongodb.DB;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.ndp.fb.constant.MongoConstants;
import com.ndp.fb.model.AdGroupStats;
import com.ndp.fb.mongo.api.AdGroupStatsHistoryMongoService;
import com.ndp.fb.util.DateFormatUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by jacky.cheng on 2015/6/29.
 */
@Service
public class AdGroupStatsHistoryMongoServiceImpl implements AdGroupStatsHistoryMongoService {
    Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private DB adHistoryDBClient;

    @Override
    public List<AdGroupStats> getAllSnap(Long adGroupId, Date sinceDay, Date untilDay, String... fields) {
        if (adGroupId == null) {
            logger.warn("adGroupId is null. return.");
            return null;
        }
        // 查询条件
        DBObject condition = new BasicDBObject();
        condition.put("adGroupId", adGroupId);
        DBObject timeObject = new BasicDBObject();
        timeObject.put("$gte", sinceDay);
        timeObject.put("$lte", untilDay);
        condition.put("updateTimeList.0", timeObject);
        DBObject dayObject = new BasicDBObject();
        dayObject.put("$gte", DateFormatUtil.formatLong10(sinceDay));
        dayObject.put("$lte", DateFormatUtil.formatLong10(untilDay));
        condition.put("day", dayObject);
        //返回字段
        DBObject keys = new BasicDBObject();
        for (String queryField : fields) {
            keys.put(queryField, 1);
        }
        DBCursor dataCur = adHistoryDBClient.getCollection(MongoConstants.TABLE_NAME_ADGROUP_STATS_BY_DAY_HISTORY).find(condition, keys).addOption(Bytes.QUERYOPTION_NOTIMEOUT);
        List<AdGroupStats> result = new ArrayList<>();
        try {
            if (dataCur == null) {
                logger.warn("没有查到统计快照数据。adGroupId={}", adGroupId);
                return null;
            }
            while (dataCur.hasNext()) {
                DBObject next = dataCur.next();
                if (next != null) {
                    AdGroupStats adGroupStats = JSON.parseObject(JSON.toJSONString(next), AdGroupStats.class);
                    List<Date> updateTimeList = (List<Date>) next.get("updateTimeList");
                    adGroupStats.setUpdateTime(updateTimeList.get(0));
                    result.add(adGroupStats);
                } else {
                    logger.error("getAll,统计数据查询有空结果。");
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        } finally {
            dataCur.close();
        }

        return result;
    }

    @Override
    public List findChangedAdGroupIds(Date startTime, Date endTime) {
        List<Long> adGroupIds = new ArrayList<>();
        // 表名
        // 查询条件
        DBObject dbObject = new BasicDBObject();
        // updateTimeList是每条统计数据的更新时间历史，第0个元素就代表了这条记录的创建时间，如果创建时间大于给定的查询开始时间则说明该记录是新的，也就表明了该AdGroup的统计数据发生了变化
        dbObject.put("$gt", startTime);
        dbObject.put("$lte", endTime);
        // distinct去重查询
        adGroupIds = adHistoryDBClient.getCollection(MongoConstants.TABLE_NAME_ADGROUP_STATS_BY_DAY_HISTORY).distinct("adGroupId", new BasicDBObject("updateTimeList.0", dbObject));
        return adGroupIds;
    }
}
